package main

import (
	"DistributeCalculator/task"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"time"
)

func main() {
	c := client{clientID: 1}
	c.clientID = 1
	rpcClient, err := c.connectToPrimary("8081", "127.0.0.1")
	if err != nil {
		log.Fatalf("链接失败, error: %v", err)
		return
	}
	req := &task.ClientRequest{
		ClientID: c.clientID,
		Task: &task.Task{
			TaskID:   &task.TaskID{TaskID: 1234},
			Operator: "+",
			Numbers:  []int32{1, 7},
			Result:   "",
		},
	}

	c.callForPushTask(rpcClient, req)
	response := c.callForPullResult(rpcClient, req.GetTask().GetTaskID())
	fmt.Printf("计算结果为%v\n", response.Task)
}

type client struct {
	clientID int32
}

func (this *client) callForPushTask(rpcClient task.TaskServiceClient, request *task.ClientRequest) {
	_, err := rpcClient.PushTask(context.Background(), request)
	if err != nil {
		log.Println(err)
		return
	}

}
func (this *client) callForPullResult(rpcClient task.TaskServiceClient, taskID *task.TaskID) *task.ResponseForClient {
	for {
		result, err := rpcClient.PullResult(context.Background(), taskID)
		if err != nil {
			fmt.Printf("还没有计算出结果，请等待...\n")
			time.Sleep(time.Second)
		} else {
			return result
		}
	}

}

//获取请求客户端
func (this *client) connectToPrimary(port string, address string) (task.TaskServiceClient, error) {
	target := address + ":" + port
	conn, err := grpc.Dial(target, grpc.WithInsecure())
	if err != nil {
		log.Printf("端口不可用, error:%v", err)
		return nil, err
	}
	rpcClient := task.NewTaskServiceClient(conn)
	return rpcClient, nil
}
